// Copyright (C) 2010 Razvan Constantin <razvan.constantin@rconst.net>
//
// This file is part of FileBow.
//
// FileBow is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// FileBow is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with FileBow.  If not, see <http://www.gnu.org/licenses/>.

// Implementation of Plugin class.

#include "ui/plugin.h"

#include <string>
#include <Poco/Path.h>

#include "common/common.h"
#include "common/strings.h"
#include "logic/navigator.h"
#include "logic/path-tree.h"
#include "logic/path-scanner.h"
#include "ui/geany-bridge.h"
#include "ui/navigate-dlg.h"

using namespace std;
using Poco::Path;

namespace filebow {

extern "C" void Plugin_OnNavigate(GtkMenuItem* menuItem, Plugin* plugin) {
  plugin->ShowNavigateDlg();
}

void GeanyMsgLogHandler(LogLevel::Value level, const string& text) {
  GB_msgwin_status_add(text.c_str());
}

Plugin::Plugin()
    : mNavigator(new Navigator) {
  RegisterLogHandler(GeanyMsgLogHandler);
  mNavigateMenu = NULL;
}

Plugin::~Plugin() {
  if (mNavigateMenu) {
    gtk_widget_destroy(mNavigateMenu);
  }
}

void Plugin::SetupMenu() {
  mNavigateMenu = gtk_menu_item_new_with_mnemonic("Navigate");
  gtk_widget_show(mNavigateMenu);
  GtkWidget* tools_menu = GB_tools_menu();
  gtk_container_add(GTK_CONTAINER(tools_menu), mNavigateMenu);
  g_signal_connect(mNavigateMenu, "activate",
                   G_CALLBACK(Plugin_OnNavigate), this);
}

void Plugin::SetupHandlers() {
}

void Plugin::SetupKeys() {
  GB_setup_keys(mNavigateMenu);
}

void Plugin::LoadProject() {
  mNavigator.reset(new Navigator());
  // mNavigator->ParseExclusionPatterns(".svn;.o;.git;.git5_specs");
  // mNavigator->SetTopSize(50);

  // Set project path.
  const gchar* geany_project_base_path = GB_geany_project_base_path();
  if (geany_project_base_path) {
    mNavigator->AddProjectPath(geany_project_base_path);
  }
  // Include opened files.
  for (int i = 0; const gchar* path = GB_document_next_valid_path(&i); ++i) {
    mNavigator->RecordPreviouslyOpened(path);
  }
}

void Plugin::HandleOpen(const string& file) {
}

void Plugin::HandleActivate(const string& file) {
  mNavigator->SetActiveFile(file);
}

void Plugin::HandleClose(const string& file) {
  mNavigator->RecordClose(file);
}

void Plugin::ShowNavigateDlg() {
  // Setup active document.
  if (GB_current_document_path()) {
    mNavigator->SetActiveFile(GB_current_document_path());
  }
  // Show dialog.
  NavigateDlg navigateDlg(mNavigator.get());
  navigateDlg.Show();
}

} // namespace filebow
